package acom.dhy.qigsaw2test

import org.junit.Test
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader

class BundleTool {
    @Test
    fun installApk() {
        val aab = File("build\\outputs\\bundle\\debug\\app-debug.aab")
        val apks = File(aab.parent, "app.apks")
//        runCommand("bundletool.bat build-apks --overwrite --local-testing --bundle $aab --output $apks")
        runCommand("bundletool.bat build-apks --overwrite --bundle $aab --output $apks")
        runCommand("bundletool.bat install-apks --apks $apks")
    }
}

fun runCommand(cmd: String) {
    val keyPath = "path"
    val path = System.getenv(keyPath)
    val process = Runtime.getRuntime().exec(cmd, arrayOf("$keyPath=$path"))
    val code = process.waitFor()
    val inputStream = if (code == 0) process.inputStream else process.errorStream
    val reader = BufferedReader(InputStreamReader(inputStream))
    val sb = StringBuilder()
    var line: String? = reader.readLine()
    while (line != null) {
        if (code == 0) println(line)
        else sb.append(line).append("\n")
        line = reader.readLine()
    }
    reader.close()
    inputStream.close()
    if (code != 0) throw Exception(sb.toString())
}